import {DELETED_CLASS, HIDDEN_PAGE_COMMENTS_ELEM_ID, HIGHLIGHT_CLASS} from "~utils/constants";
import uuidWrapper from "~utils/uuid";
import {stringifyHighlighsToViewstate} from "~manager/viewstateManager";
import { store } from "~storage/store";

const create = async (color, comments) => {
  console.log("inside highlightPage create...");
  const elem = document.getElementById(HIDDEN_PAGE_COMMENTS_ELEM_ID);

  const url = location.hostname + location.pathname;
  const highlightWithViewstate = await buildHighlightPage(url, location.href, color.color, comments);
  elem.classList.add((color === 'inherit') ? DELETED_CLASS : HIGHLIGHT_CLASS);
  elem.dataset.highlightId = highlightWithViewstate.uuid;
  elem.textContent = highlightWithViewstate.comments;
  elem.setAttribute("viewstate", highlightWithViewstate.viewstate);
  await store(url, highlightWithViewstate.viewstate);
  return highlightWithViewstate;
}

const buildHighlightPage = (url, href, color, comments) => {
  const highlight = {
    uuid: uuidWrapper(),
    color,
    href,
    ver: "*ver_page*",
    comments, // JM: comments must be the last one if in array (not here)
  }

  highlight.viewstate = stringifyHighlighsToViewstate(highlight);

  // Return the index of the new highlight:
  return highlight;
}

export default create;
